import sys
from PyQt5 import QtCore
from PyQt5.QtCore import QRect, Qt
from PyQt5.QtGui import QPixmap, QColor, QPainter, QFont
from PyQt5.QtWidgets import QWidget, QLabel, QVBoxLayout, QPushButton, QFormLayout, QHBoxLayout, QApplication, QFrame, \
    QFileDialog, QScrollArea
from utils.common import ComponentUtil
from utils.hyperlprUtil import Hyper


class PhotoView(QWidget):
    data = QtCore.pyqtSignal(list)

    def __init__(self):
        super().__init__()
        self.label = QLabel()
        self.label.setScaledContents(True)
        self.score_area = QScrollArea()
        self.score_area.setWidget(self.label)
        self.score_area.resize(640, 480)
        self.score_area.setWidgetResizable(True)
        self.car_ide_v = QVBoxLayout()
        self.form = QFormLayout()
        self.util = ComponentUtil
        self.init()

    def init(self):
        vbox = QVBoxLayout()

        frame = QFrame()
        frame.setFrameShape(QFrame.Box)
        frame.setFrameShadow(QFrame.Raised)
        frame.setStyleSheet("QFrame { border: 1px solid; }")  # 设置边框颜色和宽度
        options = QHBoxLayout()
        open_btn = QPushButton("打开图片")
        open_btn.clicked.connect(self.open_file)
        clear_btn = QPushButton("一键清除")
        clear_btn.clicked.connect(lambda : self.reset_view([]))
        options.addWidget(open_btn)
        options.addWidget(clear_btn)
        options.addStretch()
        frame.setLayout(options)

        main = QHBoxLayout()

        # 分割线
        v_split = QFrame()
        v_split.setFrameShape(QFrame.VLine)

        v_split2 = QFrame()
        v_split2.setFrameShape(QFrame.VLine)

        main.addWidget(self.score_area)
        main.addWidget(v_split)
        main.addLayout(self.car_ide_v)
        main.addWidget(v_split2)
        main.addLayout(self.form)

        vbox.addWidget(frame)
        vbox.addLayout(main)

        self.setLayout(vbox)
        self.show()
        self.reset_view([])

    def open_file(self):
        """
        打开多张图片，将第一张图片显示出来
        :return:
        """
        # 文件选择框
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file_paths, _ = QFileDialog.getOpenFileNames(self, "选择图片", "/Desktop", "图片文件 (*.png *.jpg *.jpeg *.gif *.bmp)")
        photos = []
        if file_paths:
            # pixmap = QPixmap(file_paths[0])
            # # 调整大小，例如将图片调整为宽度100px，高度自动调整以保持比例
            # pixmap = pixmap.scaled(self.width(), self.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
            for index, value in enumerate(file_paths):
                plate = Hyper().license_recognition_image(value)
                photos.append([value, plate])
        self.reset_view(photos)

    def reset_view(self, datas):
        """重新渲染页面"""
        # 先删除所有车牌
        self.util.delete_all(self.car_ide_v)
        # 删除车辆信息
        self.util.delete_all(self.form)
        # 显示第一张图片
        if datas is None or datas == []:    # 没加载打开图片的时候初始化界面
            # pixmap = self.drow_no_pic()
            self.label.setText('暂无图片，请选择图片')
            self.label.setAlignment(Qt.AlignCenter)  # 设置文本居中
            font = QFont()
            font.setPointSize(30)  # 设置字体大小为20
            self.label.setFont(font)
            self.label.setStyleSheet("""
                                            QLabel {
                                                        background-color: #ffffff; /* 背景色 */
                                                    }""")
            label_ide = QLabel('未识别车牌')
            label_ide.setFixedWidth(100)
            self.car_ide_v.addWidget(label_ide)
            label_title = QLabel('车牌号')
            label_info = QLabel('未识别车辆信息')
            self.form.addRow(label_title, label_info)
        else:
            # 显示获取到的第一张图片
            pixmap = QPixmap(datas[0][0])
            # 显示获取到第一张图片对应的车辆信息和图片
            info = QLabel(datas[0][1])
            info.setFixedWidth(100)
            self.form.addRow(QLabel('车牌号:'), info)
            # 显示车牌列表
            for index, item in enumerate(datas):
                button = QPushButton(item[1])
                button.setObjectName(item[0])       # 设置按钮点击的值，可以用 sender.objectName() 接收
                if len(item[1]) == 7:
                    button.setStyleSheet("""
                                                    QPushButton {
                                                        background-color: #0066ff; /* 背景色 */
                                                        color: #FFFFFF; /* 字体颜色 */
                                                    }
                                                """)
                elif len(item[1]) == 8:
                    button.setStyleSheet("""
                                                    QPushButton {
                                                        background-color: #33cc00; /* 背景色 */
                                                    }
                                                """)
                button.setFixedWidth(100)
                self.car_ide_v.addWidget(button)
                """
                1、动态创建button绑定事件要用lambda传值
                2、在点击任意按钮时获取的会是循环最后生成的按钮的属性，若要获取对应按钮的属性，可使用sender()
                """
                button.clicked.connect(self.show_form)
            pixmap = pixmap.scaled(self.width(), self.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
            self.label.setPixmap(pixmap)

        self.car_ide_v.addStretch()

    def show_form(self):
        sender = self.sender()
        car = sender.text()
        path = sender.objectName()
        self.util.delete_all(self.form)
        info = QLabel(car)
        info.setFixedWidth(100)
        self.form.addRow(QLabel('车牌号:'), info)
        pixmap = QPixmap(path)
        self.label.setPixmap(pixmap)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = PhotoView()
    ex.show()
    sys.exit(app.exec_())




